#! python
# -*- coding: utf-8 -*

import random
from noise import pnoise2, resort_permutation
# width, height
MATRIX = (400, 250)


def generate_altitude_noise(width=MATRIX[0], height=MATRIX[1]):
    noise_list = [bytearray(width) for y in xrange(height)]

    octaves = 4
    freq = 15.0 * octaves

    make_default_settings = False

    persistence_list = [0.555, 0.55, 0.548, 0.545, 0.54, 0.5]
    lacunarity_list = [2.05, 2.04, 2.03, 2.02, 2.0]

    if make_default_settings:
        lacunarity = 2.0
        persistence = 0.7
        altitude = 2.0
        rock_mass = 11
    else:
        lacunarity = random.choice(lacunarity_list)
        persistence = random.choice(persistence_list)

        rock_mass = 11 + (float(random.randint(0, 201)) / 100)
        altitude = 2.0 + float(random.randint(0, 100)) / 100
    # print "persistence=%f" % persistence
    # print "lacunarity=%f" % lacunarity
    # print "rock_mass=%f" % rock_mass
    # print "altitude=%f" % altitude

    for height_loop in xrange(height):
        for width_loop in xrange(width):

            value = int(pnoise2(width_loop / freq, height_loop / freq, octaves, persistence=persistence, lacunarity=lacunarity) * rock_mass + altitude)

            if value > 8: value = 8
            if value < 0: value = 0

            noise_list[height_loop][width_loop] = value

    return noise_list


def generate_chemical_noise(type_int):
    width = MATRIX[0]
    height = MATRIX[1]

    noise_list = [bytearray(width) for y in range(height)]

    octaves = 2
    freq = 10.0 * octaves

    for height_loop in xrange(height):
        for width_loop in xrange(width):

            if type_int == 1:
                # Chrome and Ferrum
                value = int(pnoise2(width_loop / freq, height_loop / freq, octaves, persistence=1.7) * 3 + 2.0)

                if value > 3: value = 3
                if value < 0: value = 0

            elif type_int == 2:
                # Silicone and Tiitan:
                freq = 15.0 * octaves

                # -> value = int(pnoise2(width_loop / freq, height_loop / freq, octaves, persistence=0.08) * 7.5 - 2.0)
                # -> less silic more titan
                value = int(pnoise2(width_loop / freq, height_loop / freq, octaves, persistence=0.35) * 5.0 - 0.3)

                if value > 2: value = 2
                if value < 0: value = 0

            elif type_int == 3:
                # Pegmatite:
                octaves = 9
                freq = 8.0 * octaves

                value = int(pnoise2(width_loop / freq, height_loop / freq, octaves, persistence=0.2, lacunarity=3.5) * 0.75 + 0.8)

                if value > 1: value = 1
                if value < 0: value = 0

            else:
                print "Error type of map (int) = %d" % type_int
                value = 0

            noise_list[height_loop][width_loop] = value

    return noise_list


def refresh_map_generator():
    resort_permutation()
